package com.hanbang.taitaigou.pay.alipay;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.hanbang.taitaigou.ui.activity.base.BaseActivity;
import com.hanbang.taitaigou.utils.http.HttpCallBack;
import com.hanbang.taitaigou.utils.http.HttpRequestParams;
import com.hanbang.taitaigou.utils.other.StringUtils;
import com.hanbang.taitaigou.utils.ui.LogUtils;
import com.hanbang.taitaigou.utils.ui.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/2/18.
 * <p/>
 * 使用方法
 * new Alipay(MeActivity.this, new Alipay.OnAlipayCallback() {
 *
 * @Override public void onCallback(boolean res, String out_trade_no, String subject, String body, String total_fee) {
 * MyLog.e("dddddddddd", out_trade_no + "   " + subject + "    " + body + "     " + total_fee);
 * <p/>
 * }
 * }).alipay("标题", "", "0.01", 1, 74, userData.getId(), "");
 */
public class Alipay {

    // 商户PID
    public static final String PARTNER = "2088121754090861";
    // 商户收款账号
    public static final String SELLER = "wy@taitaigo.cn";
    // 商户私钥，pkcs8格式
    public static final String RSA_PRIVATE = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAOup55rex/LeE/ZOeY1fTF3cp4zpF6tGURv7NPcfEZDXotGbXijr1PPYpdtN5EJTDpZzwWwn/bmxm5snYMwpMHGVpI6IC/cGl24rBULf/5GkHiz4BT4TcxapFrvtF03s6doOhcVxltuQ82giafJQvdOAM80EWqYdt3i83hG3o899AgMBAAECgYB8VcMVSa7yq0qa7CJjfUEcUHux85UCT3IhsjLqouCwq6SCtFdEfdB36vjusLTabVnH9UC6oIrUOyme/XKrpJuifoNOovohBHVw2fcpGu4u6U0NrCb9KxEjyjNQYpNgfT0shXah3RmLDbMpVN5GW46cTry/WergAdok4A4nb8janQJBAP1uGBYjnHbNjBTqDV16t84nj8Pj829rm+SPyGJR1SiLWRWs4Ed84TVSP6ax9TXbIp5Xb8itIo/uet7eGpUcZ1cCQQDuDbBkYffSGcopakunYVJIuNKL1mo3po7UUZDbrJCjwCssKV8moEf4RPdaBu7xX3IFj7R3fbsEeUjlPZNr4h9LAkEAoa+fxmAp7tHs0VsR89XbdrdezYedRDTPXN8u5St4Z0mgKGgHHxTZSf+ThHJ9E0Mfrw3xz4JGTrXDxnTFWOSqOQJBAL0vDdbI8Lz9F+eP/S25Lz5x+4l8Tg+KA4qCg//AhXZNe0HuYxr8WBXbIURfrDcQ5jm7Oe2Ycy8cAC2GoQkkvD8CQQCGjT/mfN0C8zhO4lYte6xyLCxgeitTO7kHaQwI8j+ngpJKP0V+7Ep029meH/GikoEsb4iUgt5+6n3izmGRr2e7";
    private static final int SDK_PAY_FLAG = 1;
    private BaseActivity activity = null;
    private Handler mHandler = null;
    private String serviceAddress = "http://ttgtext.hbung.com/zhifubao/notify_url.aspx";

    public Alipay(BaseActivity activity, OnAlipayCallback onAlipayCallback) {
        this.activity = activity;
        mHandler = new MyHander(activity, onAlipayCallback);
    }

    static class MyHander extends Handler {
        WeakReference<BaseActivity> act = null;
        OnAlipayCallback onAlipayCallback = null;

        public MyHander(BaseActivity a, OnAlipayCallback onAlipayCallback) {
            act = new WeakReference<BaseActivity>(a);
            this.onAlipayCallback = onAlipayCallback;
        }

        /**
         * 获取返回结果的某个值
         */
        private String getValuse(String content, String key) {
            Pattern pattern = Pattern.compile("(?<=" + key + "=\")(.+?)(?=\")");
            Matcher matcher = pattern.matcher(content);
            while (matcher.find())
                return matcher.group();
            return "";
        }
        private void isSuccess(final String resultInfo, int resultStatus) {
            if (act.get() == null) {
                return;
            }
            HttpRequestParams params = new HttpRequestParams();
            params.addBodyParameter("action", "GetZfbFinshCansMing");
            params.addBodyParameter("payment", String.valueOf(1));
            params.addBodyParameter("out_trade_no", getValuse(resultInfo, "out_trade_no"));
            params.addBodyParameter("total_fee", getValuse(resultInfo, "total_fee"));
            params.addBodyParameter("resultStatus", String.valueOf(resultStatus));
            params.addBodyParameter("success", getValuse(resultInfo, "success"));
            act.get().httpManager.post(params, new HttpCallBack<String>(act.get(), "订单生成中", false) {
                @Override
                public void onSuccess(String responseInfo) {
                    super.onSuccess(responseInfo);

                    try {
                        JSONObject json = new JSONObject(responseInfo);
                        //{"Result":0,"Msg":"支付成功"}
                        if (json.getInt("Result") == 0) {
                            if (act.get() != null) {
                                Toast.makeText(act.get(), "支付成功", Toast.LENGTH_SHORT).show();
                            }
                            if (onAlipayCallback != null) {
                                onAlipayCallback.onCallback(true, getValuse(resultInfo, "out_trade_no"), getValuse(resultInfo, "subject"), getValuse(resultInfo, "body"), getValuse(resultInfo, "total_fee"));
                            }
                        } else {
                            if (onAlipayCallback != null) {
                                onAlipayCallback.onCallback(false, getValuse(resultInfo, "out_trade_no"), getValuse(resultInfo, "subject"), getValuse(resultInfo, "body"), getValuse(resultInfo, "total_fee"));
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        if (onAlipayCallback != null) {
                            onAlipayCallback.onCallback(false, getValuse(resultInfo, "out_trade_no"), getValuse(resultInfo, "subject"), getValuse(resultInfo, "body"), getValuse(resultInfo, "total_fee"));
                        }
                    }

                }
            });
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    if (act.get() == null) {
                        return;
                    }
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     *
                     * resultStatus={9000};memo={处理成功};result={partner="2088121821860780"&seller_id="liuy@chinassc.net
                     * "&out_trade_no="021916242521011"&subject="测试的商品"&body="该测试商品的详细描述"&total_fee="0.01"
                     * &notify_url="http://notify.msp.hk/notify.htm"&service="mobile.securitypay.pay"&payment_type="1"
                     * &_input_charset="utf-8"&it_b_pay="30m"&return_url="m.alipay.com"&success="true"&sign_type="RSA"&sign=
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    LogUtils.e("ssssssssss", resultInfo);
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {

                        if (onAlipayCallback != null) {
                            onAlipayCallback.onCallback(true, getValuse(resultInfo, "out_trade_no"), getValuse(resultInfo, "subject"), getValuse(resultInfo, "body"), getValuse(resultInfo, "total_fee"));
                        }

                    } else {
                        if (onAlipayCallback != null) {
                            onAlipayCallback.onCallback(false, getValuse(resultInfo, "out_trade_no"), getValuse(resultInfo, "subject"), getValuse(resultInfo, "body"), getValuse(resultInfo, "total_fee"));
                        }
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(act.get(), "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(act.get(), "支付失败", Toast.LENGTH_SHORT).show();

                        }
                    }
                    /**
                     * 调用接口   问服务器是否真的成功了
                     */
                    //isSuccess(payResult.getResult(),resultStatus);
                    break;
                }
                default:
                    break;
            }
        }
    }


    /**
     * 生成订单号
     *
     * @param subject:商品名称
     * @param body:商品详情
     * @param price:商品价格
     * @param type:类别->1秘籍，2学习课堂，3学习资料，4拜师，5餐饮标准化
     * @param keyId：主键id
     * @param sellUserID：卖家ID
     * @param fapiaoFitle：开票抬头，餐饮标准化的时候有，其他时候没有
     */
    public void alipay(final String subject, final String body, final double price, String type, int keyId, int sellUserID, String fapiaoFitle) {
        if (!activity.isLogin(false)) {
            return;
        }
        //访问服务器生成订单号
        HttpRequestParams params = new HttpRequestParams();
        params.addBodyParameter("action", "Order_Add");
        params.addBodyParameter("type", type);
        params.addBodyParameter("keyid", String.valueOf(keyId));
        params.addBodyParameter("sellUserID", String.valueOf(sellUserID));
        params.addBodyParameter("fapiao_title", fapiaoFitle);
        params.addBodyParameter("telphone", BaseActivity.userData.getMobile());
        params.addBodyParameter("password", BaseActivity.userData.getPassword());

        activity.httpManager.post(params, new HttpCallBack<String>(activity, "订单生成中", false) {
            @Override
            public void onSuccess(String responseInfo) {
                super.onSuccess(responseInfo);
                //{"Result":1,"Msg":"参数不对"}
                //{"SPddanNum":"DD201602261032130000000001","true":"下单成功"}
                try {
                    JSONObject json = new JSONObject(responseInfo);
                    String num = json.getString("SPddanNum");
                    //去支付
                    alipay(subject, body, price, num);
                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtils.showShort(activity, "订单生成失败");
                }

            }
        });
    }

    /**
     * 开始支付
     *
     * @param subject : 商品名称
     * @param body    : 商品详情
     * @param subject : 商品价格
     * @param subject : 商品订单号   应该是调用服务器  调用接口 让服务器返回订单号
     */
    public void alipay(String subject, String body, double price, String tradeNo) {
        //1:生成订单信息
        String orderInfo = getOrderInfo(subject, body, StringUtils.roundString(price, 2), tradeNo);

        //2:对订单信息进行签名          特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
        String sign = sign(orderInfo);

        //3: 对签名后的信息 做URL编码
        try {
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //4: 合成完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();
        Log.e("ssssssssss", payInfo);


        //5必须异步调用
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(activity);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };


        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    private String sign(String content) {
        return SignUtils.sign(content, RSA_PRIVATE);
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    /**
     * create the order info. 创建订单信息
     */
    private String getOrderInfo(String subject, String body, String price, String tradeNo) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + PARTNER + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + tradeNo + "\"";

        // 商品名称
        if (!TextUtils.isEmpty(subject)) {
            orderInfo += "&subject=" + "\"" + subject + "\"";
        }

        // 商品详情
        if (!TextUtils.isEmpty(body)) {
            orderInfo += "&body=" + "\"" + body + "\"";
        }

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + price + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + serviceAddress + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        //orderInfo += "&return_url=";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }


    public interface OnAlipayCallback {
        void onCallback(boolean isSuccess, String out_trade_no, String subject, String body, String total_fee);
    }

}
